package com.iflytek.universitymanagement.config;


import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.iflytek.universitymanagement.domain.Student;
import com.iflytek.universitymanagement.exception.ServiceException;
import com.iflytek.universitymanagement.mapper.StudentMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt拦截器
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
/*

    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    @Resource
    private StudentMapper studentMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");  //header里面传过来参数
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");   //url参数  ？token=xxx
        }
        //如果不是映射到方法直接通过
//        if (handler instanceof HandlerInterceptor) {
//            AuthAccess annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
//            if(annotation != null) {
//                return true;
//            }
//        }

        //执行认证
        if (StrUtil.isBlank(token)) {
            throw new ServiceException("401", "请登录");
        }

        //获取token中的student id
        String studentId;
        try {
            studentId = JWT.decode(token).getAudience().get(0);  //JWT.decode(token) 解码 jwt token
        } catch (JWTDecodeException j) {
            throw new ServiceException("401", "请登录");
        }

        //根据token中的studentId查询数据库
        Student student = studentMapper.selectById(Integer.valueOf(studentId));
        if (student == null) {
            throw new ServiceException("401", "请登录");
        }

        //通过用户密码加密后生成一个验证器
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(student.getPassword())).build();
        try {
            jwtVerifier.verify(token);//验证token
        } catch (JWTVerificationException e) {
            throw new ServiceException("401", "请登录");
        }
        return true;
    }

*/


}